//
//  ST_SearchPlaceViewController.swift
//  btvideo
//
//  Created by mac on 2021/1/29.
//  Copyright © 2021 JarvanZhang. All rights reserved.
//

import UIKit
import SwiftyJSON
import Alamofire

class ST_SearchPlaceViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .white
        
        view.addSubview(searchBtn)
        view.addSubview(cancel_btn)
        cancel_btn.snp.makeConstraints { (make) in
            make.right.equalToSuperview()
            make.top.equalToSuperview().offset(statusBarHeight)
            make.height.equalTo(44)
            make.width.equalTo(58)
        }
        
        searchBtn.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.height.equalTo(38)
            make.centerY.equalTo(cancel_btn)
            make.right.equalTo(cancel_btn.snp.left).offset(-15)
        }
        
        
        
        
        view.addSubview(textField)
        textField.snp.makeConstraints { (make) in
            make.edges.equalTo(searchBtn).inset(UIEdgeInsets.init(top: 1, left: 33, bottom: 0, right: 16+11+3))
        }
        
        view.addSubview(delete_btn)
        delete_btn.snp.makeConstraints { (make) in
            make.width.height.equalTo(16)
            make.centerY.equalTo(searchBtn)
            make.right.equalTo(searchBtn).offset(-11)
        }
        
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.left.bottom.right.equalToSuperview()
            make.top.equalTo(cancel_btn.snp.bottom)
        }
        
        textField.becomeFirstResponder()
        
        NotificationCenter.default.addObserver(self, selector: #selector(text_did_change_handle), name: UITextField.textDidChangeNotification, object: nil)
        
    }
    
//    MARK: - Properties
    fileprivate lazy var searchBtn:UIButton = {
        
        let control = ST_SearchButtonCreater.createSearchButton()
        return control
    }()
    
    fileprivate lazy var delete_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImageForAllStates(ST_ImageUtils.imageName("search_bar_delte")!)
        control.addTarget(self, action: #selector(clear_input_handle), for: UIControl.Event.touchUpInside)
        control.alpha = 0
        return control
    }()
    
    fileprivate lazy var cancel_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setTitleForAllStates("取消")
        control.setTitleColorForAllStates(UIColor.init(hex: 0x333333)!)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium)
        control.addTarget(self, action: #selector(close_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    
    fileprivate lazy var textField:UITextField = {
       let control = UITextField()
        let attrString = NSMutableAttributedString(string: "请输入想要漫游的城市或街道")
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14),.foregroundColor: UIColor(red: 0.67, green: 0.7, blue: 0.75, alpha: 1)]
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        control.attributedPlaceholder = attrString
        control.textColor = UIColor.init(hex: 0x333333)
        control.tintColor = UIColor.init(hex: 0x333333)
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
        control.returnKeyType = .search
        control.enablesReturnKeyAutomatically = true
        control.delegate = self
        return control
    }()
    
    
    fileprivate lazy var tableView:UITableView = {
        
        let control = UITableView.init(frame: CGRect.zero, style: UITableView.Style.plain)
        
        control.contentInset = UIEdgeInsets.init(top: 10, left: 0, bottom: BTSafeAreaBottom + 30 , right: 0)
        
        control.delegate = self
        control.dataSource = self
        
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        
        
        control.register(cellWithClass: ST_SearchPlaceCell.self)
        
        
        control.separatorStyle = .none
        
        control.backgroundColor = UIColor.white
        
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        return control
    }()
    
    
    fileprivate lazy var data_array = [ST_LocationOptionCellModel]()
    
    var searchedClosure:((ST_LocationOptionCellModel)->())?
    
    deinit {
        
        NotificationCenter.default.removeObserver(self)
    }
    
    
}

extension ST_SearchPlaceViewController:UITextFieldDelegate{
    
    @objc fileprivate func clear_input_handle(){
        textField.text = nil
        self.text_did_change_handle()
    }
    
    @objc fileprivate func text_did_change_handle(){
        delete_btn.alpha = (textField.text?.isEmpty ?? true) ? 0 : 1
    }
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        
        delete_btn.alpha = (textField.text?.isEmpty ?? true) ? 0 : 1
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        
        guard let str = textField.text,!str.isEmpty else {
            return true
        }
        search(text: str)
        
        return true
    }
    
}

extension ST_SearchPlaceViewController{
    
    @objc fileprivate func search(text:String){
        
//        keywords=成都北京烤鸭&children=1&offset=20&page=1&extensions=all
        
        let afRequest = AF.request(PH.searchPlaceApi, method: HTTPMethod.get, parameters: ["key":"1e2cbec9bbef7f41b6431f7584f4e991","keywords":text,"children":1,"offset":20,"page":1,"extensions":"all"])
        
        afRequest.response { (response) in
            
            if let err = response.error{
                
                print("解析搜索位置-错误:",err)
                
            }else{
                
                if let data = response.data{
                    do {
                        
                        let swiftyJsonVar = try JSON.init(data: data)
                        
                        
                        self.data_array = swiftyJsonVar["pois"].arrayValue.map({ST_LocationOptionCellModel.init(json: $0)})
                        
                        self.tableView.reloadData()
                        
                        print("解析搜索位置json=",swiftyJsonVar)
                        
                    }
                    catch {
                        print("解析搜索位置-错误: &&&")
                    }
                }else{
                    print("解析搜索位置-错误: &&&01-")
                }
            }
        }
        
    }
    
    
    @objc fileprivate func close_handle(){
        
        self.goback_previous_controller(animated: false)
        
        
    }
    
    
    
}



extension ST_SearchPlaceViewController:UITableViewDelegate,UITableViewDataSource{
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 60
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        self.data_array.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withClass: ST_SearchPlaceCell.self, for: indexPath)
     
        cell.model = self.data_array[safe: indexPath.row]
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let item = data_array[indexPath.row]
        
        self.searchedClosure?(item)
        
        goback_previous_controller(animated: true)
        
    }
    
    
    
}




//MARK: - Cell

class ST_SearchPlaceCell: UITableViewCell {
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.selectionStyle = .none
        
        contentView.backgroundColor = .white
     
        
        contentView.addSubview(locationTitleLabel)
        locationTitleLabel.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(10)
            make.left.equalToSuperview().offset(15)
            make.height.equalTo(20)
        }
        
        contentView.addSubview(locationContentLabel)
        locationContentLabel.snp.makeConstraints { (make) in
            make.bottom.equalToSuperview().offset(-10)
            make.left.equalToSuperview().offset(15)
            make.height.equalTo(17)
        }
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
   
    fileprivate lazy var locationTitleLabel:UILabel = {
        let control = UILabel.init()
        control.textColor = UIColor(hexString: "#333333")
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium)
        return control
    }()

    fileprivate lazy var locationContentLabel:UILabel = {
        let control = UILabel.init()
        control.textColor = UIColor(hexString: "#BEC4CF")
        control.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)
        return control
    }()
    
    weak var model:ST_LocationOptionCellModel?{
        didSet{
            
            guard let m = model else { return  }
            
            locationTitleLabel.text = m.name
            
            locationContentLabel.text = m.addressStr
        }
    }
}






enum ST_SearchButtonCreater {
    
    static func createSearchButton() -> UIButton {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.backgroundColor = UIColor.init(hex: 0xF5F8FA)
        control.cornerRadius = 38/2.0
        control.setTitleColorForAllStates(UIColor.init(hex: 0xACB4C0)!)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        control.setImageForAllStates(ST_ImageUtils.imageName("搜索_icon_gray")!)
        control.contentHorizontalAlignment = .left
        control.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: 15, bottom: 0, right: 0)
        control.imageEdgeInsets = UIEdgeInsets.init(top: 0, left: 10, bottom: 0, right: 0)
        return control
    }
}
